<template>
  <div class="index_body" @click="indexBtn()">
    <div class="gaodu" :style="{height:getWindowHeight+'px'}">
      <cube-scroll
        ref="scroll"
        :data="data"
        :options="options"
        @pulling-up="onPullingUp"
        >
          <div class="box" v-for="(item,index) in data">
              <div class="right">
                  <div class="fl">
                      <div class="top_box">
                          <router-link class="top_box" :to="{ name: 'ShopDetails',query:{store_id:item.store_id,type:'itemDynamic'}}">
                            <div class="left">
                                <img :src="item.logo" alt="">
                            </div>
                            <h3 class="shop_name">{{item.name}}</h3>
                          </router-link>
                      </div>
                      <span>{{item.timemsg}}</span>
                  </div>
                  <p class="info_p" v-show="item.slice_show">{{item.slice_content}}</p>
                  <p class="info_p" v-show="item.content_show">{{item.content}}</p>
                  <a href="javascript:;" class="quanwen" @click.stop="handleFold(index)" v-show="item.slice_show && item.is_slice">全文</a>
                  <a href="javascript:;" class="quanwen" @click.stop="handleFold(index)" v-show="item.content_show && item.is_slice">收起</a>
                  <div class="img_box">
                      <img :src="img" alt="" v-for="(img,i) in item.thumb" :key="i" @click.stop="handleImgsClick(item.thumb,i)">
                  </div>

                  <div class="foot_box">
                      <p class="read_p">{{item.views}}人看过
                      </p>
                      <div class="pinglun_box" @click.stop="pinglunStatus(item.id)">
                            <i class="xiugai_icon" :style="xiugai_icon"></i>
                      </div>
                  </div>
              </div>
              <div class="dynamic_commnet" v-if="item.comment_list.length > 0">
                  <div class="item" v-for="(comment,index) in item.comment_list" @click.stop="commentStatus(item.id,comment.id)">
                      <span class="title">{{comment.user_nickname}}</span>
                      <span class="content" v-if="comment.reply_nickname">回复</span>
                      <span class="title" v-if="comment.reply_nickname">{{comment.reply_nickname}}</span>
                      <span class="content">： {{comment.content}}</span>
                  </div>
              </div>
          </div>

      </cube-scroll>
    </div>
    <div ref="bottom_h" id="dy_foot" class="" style="height:1.96rem;position: fixed;bottom: 0;left: 0;">

     </div>
        <div class="foot_pinglun" v-if="pinglun_status" @click.stop="pinglun_status=true">
          <div class="fl_box">
              <div class="input_box">
                  <cube-input
                      v-model="pinglun.value"
                      :placeholder="pinglun.placeholder"
                      :type="pinglun.type"
                      :maxlength="pinglun.maxlength"
                      :readonly="pinglun.readonly"
                      :disabled="pinglun.disabled"
                      :autofocus="pinglun.autofocus"
                      :autocomplete="pinglun.autocomplete"
                      @focus="pinglunfocus"
                      @blur="pinglunblur"
                      class="input_classbusin"
                    ></cube-input>
              </div>
              <div class="right_action">
                  <a href="javascript:;" v-if="!btn_pinglun_status"  @click.stop="btn_comment()">发布</a>
                  <a href="javascript:;" v-else>发布中..</a>
              </div>
          </div>
      </div>
      <tabbar v-show="$route.meta.navShow" :idx="1" v-else></tabbar>
  </div>
</template>
<script>
import {Throttle} from '@/util/date.js';
import tabbar from '@/components/Tabbar'
export default {
    data(){
        return {
          zw:0,
          zh:0,
          data:[],
          page:1,
          maxLen:33,
          pullUpLoad: true,
          pullUpLoadThreshold: 0,
          pullUpLoadMoreTxt: '上拉加载更多',
          pullUpLoadNoMoreTxt: '没有更多数据了喔~',
          getWindowHeight:null,
          xiugai_icon:{
              backgroundImage: "url(" + require("../assets/icon_word@2x.png") + ")",
              backgroundRepeat: "no-repeat",
              backgroundSize: "cover"
          },
          pinglun_status:false,
          btn_pinglun_status:false,
          pinglun:{
              value: '',
              placeholder: '写一个评论..',
              type: 'text',
              readonly: false,
              maxlength: 250,
              disabled: false,
              autofocus: false,
              autocomplete: false
          },
          thisDynamic_id:"",
          thisComment_id:""
        }
    },
    metaInfo: {
      title: "商家动态"
    },
    components:{
        tabbar
    },
    methods:{
        handleImgsClick(imgs,index) {
          this.initialIndex = index
          const params = {
            $props: {
              imgs: imgs,
              initialIndex: 'initialIndex', // 响应式数据的key名
              loop: false
            },
            $events: {
              change: (i) => {
                // 必须更新 initialIndex
                this.initialIndex = i
              }
            }
          }
          this.$createImagePreview({ ...params
          }).show()
        },
        //查看全部收起功能
        handleFold(index) {
          this.data[index].slice_show = !this.data[index].slice_show;
          this.data[index].content_show = !this.data[index].content_show;
        },
        loadItem:Throttle(function(){
            let that = this;
            let url = "/fang/store/dynamic_list?page="+this.page;
            that.$axios.post(url,this.$qs.stringify({
                lat:that.$store.state.latitude,
                lng:that.$store.state.longitude
            })).then(function(response){
                console.log(response);
                let res = response.data;
                if(res.status == 1){
                    console.log(res.data);
                    if(res.data.data.length > 0){
                      res.data.data.forEach(function(val,index){
                        console.log(val);
                        if(val){
                          if(val.content.length > that.maxLen){
                            val.slice_content = val.content.slice(0, that.maxLen) + "...";
                            val.is_slice = true;
                            val.slice_show = true;
                            val.content_show = false;
                          }else{
                            val.slice_content = val.content;
                            val.is_slice = false;
                            val.slice_show = true;
                            val.content_show = false;
                          }
                          let ts_time = that.caculate_time(val.created_at);
                          let msg = '';
                          if(ts_time[0] != 0){
                              msg = ts_time[0]+'天前';
                          }else if(ts_time[1] != 0){
                              msg = ts_time[1]+'小时前';
                          }else if(ts_time[2] != 0){
                              msg = ts_time[2]+'分钟前';
                          }else if(ts_time[3] != 0){
                              msg = '刚刚';
                          }
                          val.timemsg = msg;
                        }

                        that.data.push(val);
                      });
                      that.page = res.data.current_page+1;
                    }else{
                      that.$refs.scroll.forceUpdate();
                    }
                    // that.amount = res.data.item.amount;
                    // that.commission = res.data.item.commission;
                }
            })
            .catch(function(error){
                console.log(error);
            });
        },2000),
        pullUpLoadObj: function() {
          return this.pullUpLoad  ? {
            threshold: parseInt(this.pullUpLoadThreshold),
            txt: {
              more: this.pullUpLoadMoreTxt,
              noMore: this.pullUpLoadNoMoreTxt
            }
          } : false;
        },
        onPullingUp:function(){
          this.loadItem();
        },
        caculate_time(created_at){
          let now_time = new Date().getTime();
          let old_time = parseInt(created_at) * 1000;
          let time = now_time - old_time;
          let day = parseInt(time / (24 * 60 * 60));//计算整数天数
          //计算出相差天数
          day =Math.floor(time/(24*3600*1000))

          //计算出小时数
          let leave1=time%(24*3600*1000)    //计算天数后剩余的毫秒数
          let hours=Math.floor(leave1/(3600*1000))
          //计算相差分钟数
          let leave2=leave1%(3600*1000)        //计算小时数后剩余的毫秒数
          let minutes=Math.floor(leave2/(60*1000))
          //计算相差秒数
          let leave3=leave2%(60*1000)      //计算分钟数后剩余的毫秒数
          let seconds=Math.round(leave3/1000)
          return [day,hours,minutes,seconds];
      },
      //打开并记录动态ID
      pinglunStatus:function(dynamic_id){
          this.pinglun_status = true;
          this.pinglun.autofocus = true;
          //记录当前动态ID
          this.thisDynamic_id = dynamic_id;
          //记录当前商家圈ID
          this.thisComment_id = "";
      },
      //打开并记录评论ID
      commentStatus:function(dynamic_id,comment_id){
          if(!comment_id){
              let content = "不能评论自己的回复";
              this.showToastTxtOnly(content);
              return;
          }
          this.pinglun_status = true;
          this.pinglun.autofocus = true;
          console.log(dynamic_id,"++++++++++++",comment_id)
          //记录当前动态ID
          this.thisDynamic_id = dynamic_id;
          //记录当前商家圈ID
          this.thisComment_id = comment_id;
      },
      pinglunfocus:function(){
          this.pinglun_status = true;
      },
      pinglunblur:function(){
          this.pinglun_status = false;
          this.pinglun.autofocus = false;
      },
      //点击最大层div隐藏评论div
      indexBtn:function(){
          this.pinglun_status = false;
          this.pinglun.value = "";
      },
      //提交评论
      btn_comment:function(){
          let that = this;
          //后端返回_user_mark，存在证明没有注册手机号码
          let _user_mark = that.$store.state._user_mark;
          if(_user_mark){
              let content = "需要注册才能评论,去注册";
              that.createDialog(content);
              return;
          }
          let url = "/fang/store/add_dynamic_comment";
          let _token01 = that.$store.state._token01;
          let dynamic_id = that.thisDynamic_id;
          let comment_id = that.thisComment_id;
          let comment_txt = that.pinglun.value;
          if(!comment_txt){
                let content = "评论不能为空";
                that.showToastTxtOnly(content);
                return;
          }
          that.pinglun_status = true;
          that.btn_pinglun_status = true;

          const toast = that.$createToast({
              time: 5000,
              txt: ''
            })
            toast.show()
          that.$axios.post(url,that.$qs.stringify({
              content:comment_txt,
              dynamic_id:dynamic_id,
              comment_id:comment_id,
              access_token:_token01
          })).then(function(response){
               toast.hide();
               that.pinglun_status = false;
               that.btn_pinglun_status = false;
              let res = response.data;
              console.log(res,"res");
              if(res.status == 1){
                  that.pinglun.value = "";
                  let dynamic_index = that.data.findIndex(function(val, index, arr){
                      return val.id == dynamic_id;
                  });
                  console.log(dynamic_index,'dynamic_index==success')
                  if(comment_id !=""){
                      let comment_index = that.data[dynamic_index].comment_list.findIndex(function(val, index, arr){
                          return val.id == comment_id;
                      });
                      that.data[dynamic_index].comment_list.push({
                          content:comment_txt,
                          user_nickname:that.$store.state.userInfo.nickname,
                          reply_nickname:that.data[dynamic_index].comment_list[comment_index].user_nickname
                      })
                  }else{
                      that.data[dynamic_index].comment_list.push({
                          content:comment_txt,
                          user_nickname:that.$store.state.userInfo.nickname
                      })
                  }

                  let content = "评论成功~";
                  that.showToastTxtOnly(content);
              }
              else if (res.status == -1) {
                  that.noLogin();
              }else{
                  let content = res.msg;
                  that.showToastTxtOnly(content);
                  that.pinglun.value = "";
              }
          })
          .catch(function(error){
              toast.hide();
              that.pinglun_status = false;
              that.btn_pinglun_status = false;
          });
      },
      createDialog(content){
          this.$createDialog({
             type: 'confirm',
             icon: 'cubeic-alert',
             title: '提示信息',
             content: content,
             confirmBtn: {
               text: '确定',
               active: true,
               disabled: false,
               href: 'javascript:;'
             },
             cancelBtn: {
               text: '取消',
               active: false,
               disabled: false,
               href: 'javascript:;'
             },
             onConfirm: () => {
                 this.binzeronefun()
             },
             onCancel: () => {

             }
           }).show()
      },
      binzeronefun:function(){
          this.$router.push("/binzerone");
      },
      showToastTxtOnly(text) {
       this.toast = this.$createToast({
         txt: text,
         type: 'txt'
       })
       this.toast.show()
     }
    },
    computed: {
      options() {
        return {
          pullUpLoad: this.pullUpLoadObj,
          scrollbar: true
        }
      }
    },
    mounted() {
        document.getElementsByTagName("body")[0].className="address_active";
        this.loadItem();
        let that = this;
        //获取屏幕的宽度
        window.onresize = () => {
          return (() => {
              window.screenWidth = document.body.clientWidth;
              that.screenWidth = window.screenWidth;
            })();
        }
        if(that.screenWidth && that.screenWidth == 320){
            that.maxLen_v = 33;
            that.maxLen = 33;
        }

        this.getWindowHeight = (document.documentElement.clientHeight || document.body.clientHeight) - this.$refs.bottom_h.offsetHeight;
    },
    beforeCreate:function(){
        document.getElementsByTagName("body")[0].className="address_active_bg";
    },
    activated:function(){
        //使用keep-alive以后进入页面只会触发activated
        document.getElementsByTagName("body")[0].className="address_active_bg";
    },
    beforeDestroy: function() {
        document.body.removeAttribute("class","address_active_bg");
    },
    deactivated:function(){
        //deactivated使用keep-alive以后推出页面只会触发deactivated
        document.body.removeAttribute("class","address_active_bg");
    }
}
</script>
<style  lang="stylus" rel="stylesheet/stylus">
.scroll-wrapper
  .cube-pulldown-wrapper
    .before-trigger
      font-size: 30px
      line-height: 30px
      align-self: flex-end
      span
        display: inline-block
        transition: all 0.3s
        color: #666
        &.rotate
          transform: rotate(180deg)
    .after-trigger
      .refresh-text
        color: grey
.scroll-list-wrap
  border: 1px solid rgba(0, 0, 0, 0.1)
  border-radius: 5px
  transform: rotate(0deg) // fix 子元素超出边框圆角部分不隐藏的问题
  overflow: hidden
.foods-wrapper
  .food-item
    display: flex
    padding: 18px
    border-bottom: 1px solid rgba(7, 17, 27, 0.1)
    &:last-child
      border-none()
      margin-bottom: 0
    .icon
      flex: 0 0 57px
      margin-right: 10px
    .food-content
      flex: 1
      .name
        margin: 2px 0 8px 0
        height: 14px
        line-height: 14px
        font-size: 14px
        color: rgb(7, 17, 27)
      .description, .extra
        line-height: 10px
        font-size: 10px
        color: rgb(147, 153, 159)
      .description
        line-height: 12px
        margin-bottom: 8px
      .extra
        .count
          margin-right: 12px
      .price
        font-weight: 700
        line-height: 24px
        .now
          margin-right: 8px
          font-size: 14px
          color: rgb(240, 20, 20)
        .old
          text-decoration: line-through
          font-size: 10px
          color: rgb(147, 153, 159)
      .cartcontrol-wrapper
        position: absolute
        right: 0
        bottom: 12px
</style>
<style scoped>
.index_body{
    height: 100%;
}
.index_body > .gaodu{
    position: absolute;
    top: 0;
    left: 0;
}
.box {
  position: relative;
  padding: .8rem .78rem;
  background: #FFFFFF;
  margin-bottom: .4rem;
  margin-left: .44rem;
  margin-right: .44rem;
}
.box .top_box{
    display: flex;
    justify-content: center;
    align-items: center;
}
.box .right .fl .left {
    display: inline-block;
  width: 1.44rem;
  height: 1.44rem;
  border-radius: 50%;
  flex: none;
}

.box .right .fl .left img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.box .right {
  text-align: left;
}
.box .right .fl{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    height: 1.44rem;
}
.box .right .fl .shop_name {
    display: inline-block;
  font-size: .64rem;
  color: #292929;
  font-weight: 600;
  padding-left: .48rem;
}
.box .right .fl > span{
    font-size: .48rem;
    color: #818181;
    font-weight: 500;
    white-space: nowrap;
}

.box .right .info_p {
  font-size: .64rem;
  color: #292929;
  margin-top: .64rem;
  margin-bottom: .32rem;
  line-height: .98rem;
  word-wrap: break-word;
  word-break: break-all;
}
.box .right .img_box {
  overflow: hidden;
  font-size: 0;
}

.box .right .img_box img{
  display: inline-block;
  display: inline-block;
  width: 3.2rem;
  height: 3.16rem;
  margin-right: .36rem;
  margin-bottom: .36rem;
  border-radius: .1rem;
}
/* .box .right .img_box img:nth-child(odd) {
  width: 6.52rem;
  height: 4.2rem;
  margin-right: .44rem;
}
.box .right .img_box img:nth-child(even) {
  width: 4.2rem;
  height: 4.2rem;
} */

.box .right .quanwen {
  display: inline-block;
  font-size: .56rem;
  font-weight: bold;
  color: #44677f;
  margin-bottom: .8rem;
}
.box .right .foot_box{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}
.box .right .foot_box .read_p{
    font-size: .48rem;
    font-weight: 500;
    color: #818181;
    text-align: left;
}
.box .right .foot_box .pinglun_box{
    width: 1.5rem;
    height: 1rem;
    display: flex;
    justify-content: center;
    align-items: center;
}
.box .right .foot_box .pinglun_box .xiugai_icon{
    display: block;
    width: .56rem;
    height: .56rem;
}
.dynamic_commnet{
    text-align: left;
    margin-top: 0.6rem;
}
.dynamic_commnet .item{
    margin: 0.6rem 0;
}
.dynamic_commnet .item .title{
    color: #44677f;
}
.dynamic_commnet .item .content{
    color: #535353;
}
.foot_pinglun{
    width: 100%;
    height: 2.04rem;
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 999;
    background: #fafafa;
}
.foot_pinglun .fl_box{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}
.foot_pinglun .fl_box .input_box{
    margin-left: .8rem;
    flex: 1;
    padding: 0;

}
.foot_pinglun .fl_box .input_box .input_classbusin  > input{
    display: block;
    width: 100%;
    height: 1.2rem;

}
.foot_pinglun .fl_box .right_action{
    width: 4rem;
}
.foot_pinglun .fl_box .right_action > a{
    display: block;
    width: 2rem;
    margin: 0 auto;
    padding:.2rem;
    border-radius: .2rem;
    color: #ffffff;
    font-size: .56rem;
    background: #363944;

}
</style>
